package com.xuanzheng.company.service.impl;

import com.xuanzheng.company.dao.CompanyDao;
import com.xuanzheng.company.dao.CompanyEmployeeDao;
import com.xuanzheng.company.dao.impl.CompanyDaoImpl;
import com.xuanzheng.company.dao.impl.CompanyEmployeeDaoImpl;
import com.xuanzheng.company.entity.CompanyEmployee;
import com.xuanzheng.company.service.CompanyEmployeeService;

import java.math.BigDecimal;
import java.util.List;

public class CompanyEmployeeServiceImpl implements CompanyEmployeeService {
    private final CompanyEmployeeDao companyEmployeeDao;
    private final CompanyDao companyDao;
    
    public CompanyEmployeeServiceImpl() {
        this.companyEmployeeDao = new CompanyEmployeeDaoImpl();
        this.companyDao = new CompanyDaoImpl();
    }

    @Override
    public boolean submitApplication(CompanyEmployee companyEmployee) {
        // 检查用户是否已在某公司工作
        if (companyEmployeeDao.isUserInCompany(companyEmployee.getUserId())) {
            return false;
        }
        
        // 检查是否已经向该公司申请
        CompanyEmployee existingApplication = companyEmployeeDao.getApplicationByUserIdAndCompanyId(
                companyEmployee.getUserId(), companyEmployee.getCompanyId());
        if (existingApplication != null) {
            // 如果有待审核的申请，不允许再次申请
            if (existingApplication.getStatus() == 0) {
                return false;
            }
            
            // 如果申请已被拒绝，允许重新申请，需要更新现有申请记录
            if (existingApplication.getStatus() == 2) {
                // 更新申请状态为待审核(0)，清空拒绝原因，更新申请理由
                return companyEmployeeDao.updateApplicationStatusForReapply(existingApplication.getId(), companyEmployee.getReason());
            }
            
            // 如果申请已通过，不允许再次申请
            if (existingApplication.getStatus() == 1) {
                return false;
            }
        }
        
        // 没有申请记录，创建新申请
        return companyEmployeeDao.addApplication(companyEmployee);
    }

    @Override
    public boolean reviewApplication(String id, int status, String position, BigDecimal baseSalary, String rejectReason) {
        if (status != 1 && status != 2) {
            return false;
        }
        
        CompanyEmployee application = companyEmployeeDao.getApplicationById(id);
        if (application == null || application.getStatus() != 0) {
            return false;
        }
        
        String employeeNumber = null;
        if (status == 1) { // 通过
            // 获取下一个员工编号
            employeeNumber = companyDao.getNextEmployeeNumber(application.getCompanyId());
            
            // 更新公司员工数量
            companyDao.updateEmployeeCount(application.getCompanyId(), 1);
        }
        
        return companyEmployeeDao.updateApplicationStatus(id, status, employeeNumber, position, baseSalary, rejectReason);
    }

    @Override
    public CompanyEmployee getApplicationById(String id) {
        return companyEmployeeDao.getApplicationById(id);
    }

    @Override
    public CompanyEmployee getUserLatestApplication(String userId) {
        return companyEmployeeDao.getLatestApplicationByUserId(userId);
    }

    @Override
    public List<CompanyEmployee> getApplicationsByUserId(String userId) {
        return companyEmployeeDao.getApplicationsByUserId(userId);
    }

    @Override
    public List<CompanyEmployee> getApplicationsByCompanyId(String companyId) {
        return companyEmployeeDao.getApplicationsByCompanyId(companyId);
    }

    @Override
    public List<CompanyEmployee> getApplicationsByCompanyIdAndStatus(String companyId, int status) {
        return companyEmployeeDao.getApplicationsByCompanyIdAndStatus(companyId, status);
    }

    @Override
    public CompanyEmployee getApplicationByUserIdAndCompanyId(String userId, String companyId) {
        return companyEmployeeDao.getApplicationByUserIdAndCompanyId(userId, companyId);
    }

    @Override
    public boolean canUseFeatures(String userId) {
        // 首先检查用户是否已加入公司
        boolean isInCompany = companyEmployeeDao.isUserInCompany(userId);
        if (!isInCompany) {
            return false;
        }
        
        // 检查用户是否有离职申请
        CompanyEmployee resignation = companyEmployeeDao.getResignationByUserId(userId);
        if (resignation != null && resignation.getStatus() == 3) {
            // 有待审核的离职申请，也允许使用功能
            return true;
        }
        
        // 获取用户当前所在的公司
        CompanyEmployee employeeInfo = null;
        List<CompanyEmployee> applications = companyEmployeeDao.getApplicationsByUserId(userId);
        for (CompanyEmployee app : applications) {
            if (app.getStatus() == 1) { // 已通过的申请
                employeeInfo = app;
                break;
            }
        }
        
        if (employeeInfo == null) {
            return false;
        }
        
        // 检查公司状态
        String companyId = employeeInfo.getCompanyId();
        if (companyId == null) {
            return false;
        }
        
        // 获取公司信息
        com.xuanzheng.company.entity.Company company = companyDao.getCompanyById(companyId);
        if (company == null) {
            return false;
        }
        
        // 只有公司状态为1（正常）时，员工才能使用系统功能
        return company.getStatus() == 1;
    }
    
    @Override
    public List<CompanyEmployee> getEmployeesByCompanyId(String companyId) {
        return companyEmployeeDao.getEmployeesByCompanyId(companyId);
    }
    
    @Override
    public List<CompanyEmployee> searchEmployees(String companyId, String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return getEmployeesByCompanyId(companyId);
        }
        return companyEmployeeDao.searchEmployees(companyId, keyword.trim());
    }
    
    @Override
    public CompanyEmployee getEmployeeDetail(String id) {
        return companyEmployeeDao.getEmployeeDetail(id);
    }
    
    @Override
    public boolean updateEmployeeInfo(String id, String position, BigDecimal baseSalary) {
        if (position == null || position.trim().isEmpty() || baseSalary == null || baseSalary.compareTo(BigDecimal.ZERO) < 0) {
            return false;
        }
        return companyEmployeeDao.updateEmployeeInfo(id, position.trim(), baseSalary);
    }
    
    @Override
    public boolean fireEmployee(String id) {
        if (id == null || id.trim().isEmpty()) {
            return false;
        }
        return companyEmployeeDao.fireEmployee(id);
    }

    @Override
    public CompanyEmployee getByUserId(String userId) {
        if (userId == null || userId.trim().isEmpty()) {
            return null;
        }
        
        List<CompanyEmployee> applications = companyEmployeeDao.getApplicationsByUserId(userId);
        if (applications == null || applications.isEmpty()) {
            return null;
        }
        
        // 查找状态为1（已通过）的申请
        for (CompanyEmployee app : applications) {
            if (app.getStatus() == 1) { // 已通过的申请
                return app;
            }
        }
        
        return null;
    }
    
    @Override
    public int countEmployeesByCompanyId(String companyId) {
        if (companyId == null || companyId.trim().isEmpty()) {
            return 0;
        }
        return companyEmployeeDao.countEmployeesByCompanyId(companyId);
    }
    
    @Override
    public List<CompanyEmployee> getCompanyEmployees(String companyId) {
        if (companyId == null || companyId.trim().isEmpty()) {
            return java.util.Collections.emptyList();
        }
        return companyEmployeeDao.getEmployeesByCompanyId(companyId);
    }
    
    @Override
    public List<CompanyEmployee> searchCompanyEmployees(String companyId, String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return getCompanyEmployees(companyId);
        }
        return companyEmployeeDao.searchEmployees(companyId, keyword.trim());
    }
    
    @Override
    public boolean submitResignation(String userId, String reason) {
        if (userId == null || userId.trim().isEmpty() || reason == null || reason.trim().isEmpty()) {
            return false;
        }
        
        // 获取用户当前的公司员工记录
        CompanyEmployee employee = getByUserId(userId);
        if (employee == null) {
            return false;
        }
        
        // 检查是否已有离职申请
        CompanyEmployee resignation = companyEmployeeDao.getResignationByUserId(userId);
        if (resignation != null) {
            return false; // 已有待处理的离职申请
        }
        
        // 提交离职申请
        return companyEmployeeDao.submitResignation(employee.getId(), reason.trim());
    }
    
    @Override
    public boolean reviewResignation(String id, int status) {
        if (id == null || id.trim().isEmpty()) {
            return false;
        }
        
        // 状态只能是1(拒绝离职)或4(批准离职)
        if (status != 1 && status != 4) {
            return false;
        }
        
        return companyEmployeeDao.reviewResignation(id, status);
    }
    
    @Override
    public CompanyEmployee getUserResignation(String userId) {
        if (userId == null || userId.trim().isEmpty()) {
            return null;
        }
        
        return companyEmployeeDao.getResignationByUserId(userId);
    }
    
    @Override
    public List<CompanyEmployee> getResignationsByCompanyId(String companyId) {
        if (companyId == null || companyId.trim().isEmpty()) {
            return null;
        }
        
        return companyEmployeeDao.getResignationsByCompanyId(companyId);
    }
    
    @Override
    public boolean removeAllCompanyRelations(String userId) {
        if (userId == null || userId.trim().isEmpty()) {
            return false;
        }
        
        // 获取用户当前的公司关系
        CompanyEmployee employeeInfo = getByUserId(userId);
        if (employeeInfo != null) {
            // 如果用户在公司中，更新公司员工数量
            companyDao.updateEmployeeCount(employeeInfo.getCompanyId(), -1);
            
            // 将用户与公司的关系状态更改为已离职(4)
            companyEmployeeDao.updateApplicationStatus(employeeInfo.getId(), 4, 
                    employeeInfo.getEmployeeNumber(), employeeInfo.getPosition(), 
                    employeeInfo.getBaseSalary(), null);
        }
        
        // 将用户所有待处理的申请都设置为已取消
        return companyEmployeeDao.cancelAllPendingApplications(userId);
    }
} 